/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

const { pool } = require('../utils/db')

exports.getHistoryResults = async (req, res) => {
  try {
    const page = Number(req.query.page) || 1
    const limit = Number(req.query.limit) || 10
    const offset = (page - 1) * limit

    // 如果需要，确保 limit 和 offset 是有效的数字
    if (isNaN(limit) || isNaN(offset)) {
      return res.status(400).json({
        code: 400,
        message: 'Invalid page or limit'
      })
    }

    const [results] = await pool.execute(
      `SELECT * FROM macau_history_results ORDER BY time DESC LIMIT ${limit} OFFSET ${offset}`
    )

    // 获取总记录数
    const [countResult] = await pool.execute(`SELECT COUNT(*) AS total FROM macau_history_results`)
    const total = countResult[0].total

    const [accuracy_list] = await pool.execute(`SELECT accuracy FROM macau_history_results ORDER BY time ASC`)

    res.json({
      code: 200,
      message: '成功',
      data: {
        list: results,
        accuracy_list,
        pagination: {
          total,
          currentPage: page,
          pageSize: limit,
          totalPages: Math.ceil(total / limit)
        }
      }
    })
  } catch (error) {
    console.error('查询失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    })
  }
}
